package com.yuanluludev.pgy.update

import androidx.lifecycle.MutableLiveData
import com.pgyer.pgyersdk.model.CheckSoftModel
import com.yuanluludev.lib_base.base.BaseViewModel
import com.yuanluludev.lib_base.net.errorMsg
import com.yuanluludev.lib_utils.util.LogUtils
import com.yuanluludev.pgy.PgyConstants.APK_DOWNLOAD_PATH
import rxhttp.toDownload
import rxhttp.wrapper.param.RxHttp

/**
 * yuanLuLu
 * download view Model
 */
class PgyUpdateViewModel : BaseViewModel() {

    companion object {

        const val DOWNLOAD_FAILED = 1001
    }

    //是否隐藏下载弹框
    val isDismissDownloadDialog = MutableLiveData<Boolean>()

    //下载进度
    val downloadProgress = MutableLiveData<Int>()

    //是否下载成功
    val apkPath = MutableLiveData<String>()

    fun downloadAPK(checkSoftModel: CheckSoftModel) {
        LogUtils.dTag("pgy"," APK_DOWNLOAD_PATH =  $APK_DOWNLOAD_PATH")
        launch(
            showLoading = false,
            block = {
                val filePath = RxHttp.get(checkSoftModel.downloadURL)
                    .toDownload(APK_DOWNLOAD_PATH) {
                        downloadProgress.value = it.progress
                    }
                    .await()

                //先隐藏弹窗再安装
                isDismissDownloadDialog.value = true

                apkPath.value = filePath
            },
            error = {
                postErrorValue(DOWNLOAD_FAILED, it.errorMsg)
            }
        )

    }

}